﻿using System;

namespace Boardgame
{
    /// <summary>
    /// Zero-based square coordinate with origin at lower left.
    /// </summary>
    public struct Cell
    {
        private int x;
        private int y;

        /// <summary>
        /// Make a square coordinate from the supplied values.
        /// </summary>
        /// <param name="x">Horizontal position from left.</param>
        /// <param name="y">Vertical position from bottom.</param>
        public Cell (int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        /// <summary>
        /// Gets the horizontal position of the square with the leftmost square at position 0.
        /// </summary>
        public int X
        { get { return x; } }

        /// <summary>
        /// Gets the vertical position of the square with the bottom square at position 0.
        /// </summary>
        public int Y
        { get { return y; } }


        /// <summary>
        /// Returns the coordinate as text with X starting at <em>a</em> and Y starting at <em>1</em>.
        /// </summary>
        /// <returns>Coordinate as text.</returns>
        public override string ToString ()
        {
            if (x < 26)
                return ((char) ('a'+x)).ToString() + (y+1);

            int nd = 2, x1 = x - 26;
            for (int lim = 26*26; x1 >= lim; lim *= 26)
            {
                ++nd;
                x1 -= lim;
            }

            string result = "";
            do
            {
                int d0;
                x1 = Math.DivRem (x1, 26, out d0);
                result = ((char) ('a'+d0)).ToString() + result;
            } while (--nd > 0);

            return result + (y+1);
        }
    }
}
